package com.zgscwjm.taobaphelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zgscwjm.taobaphelper.b.a;
import com.zgscwjm.taobaphelper.exutils.MyBaseConfig;
import com.zgscwjm.taobaphelper.exutils.StringUtils;
import com.zgscwjm.taobaphelper.ui.ab;
import com.zgscwjm.taobaphelper.ui.ad;
import com.zgscwjm.taobaphelper.ui.handler_updateact;
import com.zgscwjm.taobaphelper.ui.thread_getversion;
import com.zgscwjm.taobaphelper.ui.thread_install_sogou;
import com.zgscwjm.taobaphelper.ui.thread_install_taobao;
import com.zgscwjm.taobaphelper.xp.FileManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

/**
 * 更新activity 对应UpdateActivity
 */
// TODO: 17-3-1 待翻译
public class UpdateActivity extends Activity {


    private TextView tv_appname; //对应原变量e
    private TextView tv_versionname;  //对应原变量f
    public TextView tv_updateresulttip; //对应原变量g
    public ProgressBar pg_down = null; // 对应原变量q
    public static String TAG = "UpdateActivity";
    private int tbstepcode = 9001;
    private int mystepcode = 9002;
    private int sogoustepcode = 90021;
    private int tbfilelength = 20971520;
    private int sogoufilelength = 15728640;
    public boolean o = false; //这个值都没有用到～～

    public int r;
    public int s = 0;
    public DecimalFormat h = new DecimalFormat("#.00");
    public int i = 0;


    public static ProgressDialog dialog;

    public static int code = 1; //原变量j
    public static int Type = 505; //原变量c
    public static String pathstring = StringUtils.EMPTY; // 原变量 b
    public static String downloadurl = StringUtils.EMPTY; // 原变量 a

    public String packgename = StringUtils.EMPTY; //原变量 l
    private String appname = StringUtils.EMPTY; //原 变量k
    public static String versionname = "1.0";//原变量m


    public Handler handler = new handler_updateact(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        tv_appname = (TextView) findViewById(R.id.AppName);
        tv_versionname = (TextView) findViewById(R.id.VersionName);
        tv_updateresulttip = (TextView) findViewById(R.id.UpdateResultTip);
        pg_down = (ProgressBar) findViewById(R.id.down_pb);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.getInt("step") == tbstepcode) {
            appname = MyBaseConfig.TBappname;
            packgename = MyBaseConfig.TBpacgename;
            code = 1;
            pathstring = FileManager.TBDownPath;
            Type = bundle.getInt("actionType");

        }
        if (bundle != null && bundle.getInt("step") == mystepcode) {
            appname = MyBaseConfig.Myappname;
            packgename = MyBaseConfig.Mypackagename;
            code = 4;
            pathstring = FileManager.ConfigDownPath;
            Type = bundle.getInt("actionType");
        }
        if (bundle != null && bundle.getInt("step") == sogoustepcode) {
            appname = MyBaseConfig.Sogouappname;
            packgename = MyBaseConfig.Sogoupackagename;
            code = 2048;
            pathstring = FileManager.SogouDownPath;
        }
        tv_appname.setText(appname);
        tv_versionname.setText("当前版本" + getVersionname(this, packgename));
        int versioncode = getVersioncode((Context) this, packgename);

        if (versioncode <= 0 && packgename.contains(MyBaseConfig.taobaokeyword)) {
            File file = new File(FileManager.TBInstallPath);
            if (file.exists() && file.length() > tbfilelength) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("发现本地有淘宝安装包，是否直接安装？");
                builder.setTitle("发现安装包");
                builder.setPositiveButton("直接安装", new click_installtaobao(this));
                builder.setNegativeButton("去下载", new click_getversion(this));
                builder.create().show();
                return;
            }
        }
        if (versioncode <= 0 && packgename.equals(MyBaseConfig.Sogoupackagename)) {
            File file = new File(FileManager.SogouInstallPath);
            if (file.exists() && file.length() > sogoufilelength) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("发现本地有搜狗浏览器安装包，是否直接安装？");
                builder.setTitle("发现安装包");
                builder.setPositiveButton("直接安装", new click_installsogou(this));
                builder.setNegativeButton("去下载", new click_getversion2(this));
                builder.create().show();
                return;
            }
        }
        GetVersion();
    }

    /**
     * 对应原来的b方法;获取版本name；
     *
     * @param context
     * @param str
     * @return
     */
    public static String getVersionname(Context context, String str) {
        try {
            return context.getPackageManager().getPackageInfo(str, 0).versionName;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return StringUtils.EMPTY;
        }
    }

    /**
     * 对应原来的方法a; 获取版本code
     *
     * @param context
     * @param str
     * @return
     */
    public static int getVersioncode(Context context, String str) {
        try {
            return context.getPackageManager().getPackageInfo(str, 0).versionCode;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return -1;
        }

    }

    /**
     * 生成一个dialo，提炼出来的方法;
     *
     * @param msg
     */
    public void buildDialog(String msg) {
        dialog = new ProgressDialog(this);
        dialog.setMessage(msg);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.show();
    }

    /**
     * 替代原c方法
     */
    public final void GetVersion() {
        buildDialog("版本获取中...");
        new Thread(new thread_getversion(this)).start();
    }

    /**
     * 替代b方法;
     */
    public final void InstallTB() {
        buildDialog("正在安装中");
        new Thread(new thread_install_taobao(this)).start();
    }

    /**
     * 替代a方法;
     */
    public final void Installsogou() {
        buildDialog("正在安装中");
        new Thread(new thread_install_sogou(this)).start();
    }

    /**
     * 更改setting的一些配置 对应以前的f方法
     */
    public final void notifysetting() {
        String str = "/data/data/com.android.providers.settings/databases/settings.db";
        if (!new File(str).exists()) {
            a.c(" touch " + str);
            a.c(" chown system:system " + str);
            a.c(" chmod 600 " + str);
        }
    }

    public static void getNewupdata(UpdateActivity updateActivity) {

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("发现新版本");
        stringBuffer.append(updateActivity.appname);
        stringBuffer.append(versionname);
        AlertDialog.Builder builder = new AlertDialog.Builder(updateActivity);
        builder.setMessage(stringBuffer.toString());
        builder.setTitle("软件升级");
        builder.setPositiveButton("更新", new ab(updateActivity));
        builder.setPositiveButton("暂不更新", new ad(updateActivity));
        builder.create().show();
    }

    public   int a(String str,File file){   // FIXME: 2017/3/14  作者：伏仲   写不下去了。下次有空写
        InputStream inputStream;
        HttpURLConnection httpURLConnection;
        FileOutputStream fileOutputStream;
        InputStream inputStream1;
        Throwable th;
        FileOutputStream fileOutputStream1;
        Message msg=this.handler.obtainMessage();
            try {
                HttpURLConnection httpURLConnection1= (HttpURLConnection) new URL(str).openConnection();
                try {
                    httpURLConnection1.setRequestProperty("User-Agent","PacificHttpClient");
                    httpURLConnection1.setConnectTimeout(10000);
                    httpURLConnection1.setReadTimeout(20000);
                    this.r=httpURLConnection1.getContentLength();
                    if (httpURLConnection1.getResponseCode()==404)
                    {
                        if (httpURLConnection1!=null)
                        {
                            httpURLConnection1.disconnect();
                        }
                        return 0;
                    }
                    FileOutputStream fileOutputStream2;
                    inputStream=httpURLConnection1.getInputStream();

                    try {
                        fileOutputStream2=new FileOutputStream(file,false);
                    }
                    catch (Exception e)
                    {
                        httpURLConnection=httpURLConnection1;

                    }
                }
                catch (Exception e)
                {

                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return 0;
    }

}
